package com.chenyi.leetcode.editor.cn;

import java.util.Arrays;

/**
 * [349]两个数组的交集
 * @author by chenyi
 * @className IntersectionOfTwoArrays
 * @date 2022-08-27 16:54:47
 */
public class IntersectionOfTwoArrays{
    public static void main(String[] args) {
        Solution solution = new IntersectionOfTwoArrays().new Solution();
        System.out.println(
                Arrays.toString(
                        solution
                                .intersection
                                        (new int[]{1, 2, 2, 1}, new int[]{2, 2})));
    }
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int nums1Length = nums1.length;
        int nums2Length = nums2.length;
        int nums1Index = 0;
        int nums2Index = 0;
        int[] arr = new int[Math.max(nums1Length, nums2Length)];
        int arrIndex = 0;
        while (nums1Index < nums1Length && nums2Index < nums2Length) {
            if (nums1[nums1Index] == nums2[nums2Index]) {
//                if (arrIndex == 0 || nums1[nums1Index] != arr[arrIndex - 1]) {
                    arr[arrIndex++] = nums1[nums1Index];
//                }
                nums1Index++;
                nums2Index++;
            } else if (nums1[nums1Index] < nums2[nums2Index]) {
                nums1Index++;
            } else {
                nums2Index++;
            }
        }
        return Arrays.copyOfRange(arr, 0, arrIndex);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}
